<?php
namespace app\service\controller;

use app\common\logic\OldRecord;
use app\common\logic\RecordSumToday;
use app\common\logic\User;
use my\wechat\Chat;
use my\wechat\Message;

class Signinout
{
    public function index()
    {
        $_data = str_replace("&quot;", "\"", input('data'));
        $_sign = input("sign");
        $_stime = input("stime");

        $sign = $this->getSign($_stime);
        $code = $_sign == $sign ? 0 : -1;

        error_log("code:{$code}  stime:{$_stime}  _sign:{$_sign}  data:{$_data}\r\n", 3, "record.txt");

        if ($code == 0) {
            $data = json_decode($_data, true);
            $records = $this->parseData($data);
            $oldRecord = new OldRecord();

            $id = 0;
            foreach ($records as $r) {
                $oldRecord->data($r, true)->isUpdate(false)->save();
                $id = $oldRecord->id;
                $this->foreach_message($r);
            }
            $code = $id > 0 ? 0 : -1;
        }
        return json(['code' => $code]);
    }

    private function parseData($data)
    {
        $records = array();
        foreach ($data as $dev) {
            $devName = $dev["devName"];
            foreach ($dev["list"] as $list) {
                $userId = $list["userId"];
                foreach ($list["time"] as $time) {
                    $record = array("userId" => $userId, "time" => $time, 'from' => $devName);
                    array_push($records, $record);
                }
            }
        }
        return $records;
    }

    private function getSign($stime)
    {
        $appId = "100018";
        $appSecret = "f33e6b9465c2bee511cb5e6a60794e43";
        $token = "";

        $sign = md5($appId . $appSecret . $stime . $token);
        return $sign;
    }

    private function foreach_message($r)
    {
        if ($r['time'] < strtotime(date("Y-m-d")))
            return false;
        $userId = $r['userId'];
        $userTime = date('Y-m-d H:i:s', $r['time']);
        $user = RecordSumToday::get(['id' => $userId]);
        $userName = $user['name'];
        $userDept = $user['dept'];
        $userCount = $user['count'];
        $useInfo = empty($userName) ? "打卡" : ($userCount % 2 == 1 ? "签到" : "签退");
        $this->send(
            $userId,
            "{$useInfo}成功, 今日第{$userCount}次打卡",
            "{$useInfo}成功, 今日第{$userCount}次打卡\n{$userTime}"
        );

        return true;
    }

    private function send($user, $content, $mess)
    {
        Message::$touser = $user;
        Message::$agentid = c('wx_kq_agentid');
        $retB = Message::send('text', $content);

        $dept_id = User::where(['userid' => $user])->value('department');
        $chat = \app\common\logic\Chat::get(['optional' => ['like', "%,{$dept_id},%"]]);
        $chatid = $chat['chatid'];
//        $group_id = strlen($user) == 3 ? "dkxxtzzyq" : "xdkxxtzzyq";
        $retI = Chat::sendGroup($user, $chatid, $mess);

        $suc = $retB ? "success" : Message::$error;
        $suc .= $retI ? "success" : Chat::$error;

        return $suc;
    }
}